import { useEffect, useState,useRef } from 'react'

const Zero = n => n >= 10? n :'0' + n   

const format = (ms) => {
  const h = Zero(Math.floor(ms / 1000 /60 / 60))
  const m = Zero(Math.floor(ms / 1000 /60 % 60))
  const s = Zero(Math.floor(ms / 1000 % 60))
  return `${h}:${m}:${s}`
}

export const useCount = (ms) => {
  const [time,setTime] = useState('')
  const [isRunning,setIsrunning] = useState(true)
  const count = useRef(ms)
  const timer = useRef(null)
  const stop = () => {
    setIsrunning(false)
    clearInterval(timer.current)
  }

  useEffect(() => {
    setTime(format(count.current))
    timer.current = setInterval(() => {
      count.current -= 1000 
      setTime(format(count.current))
      if(count.current <= 0) {
        stop()
      }
    },1000)
    return stop
  },[]) 
  
  return {
    time,
    stop,
    isRunning
  }
}